<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix header-box">
        <span>学生管理</span>
        <el-input placeholder="请输入内容" v-model="inputName" style="width: 300px;" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="search(true)"></el-button>
        </el-input>
      </div>
      <div style="min-width:1200px">
        <el-table stripe :data="tableData.slice((currentPage4 - 1) * pageSize, currentPage4 * pageSize)"
          style="width: 100%">
          <el-table-column prop="id" label="id" align="center"  />
          <el-table-column prop="grade" label="年级"  align="center" />
          <el-table-column prop="major" label="专业"  align="center" />
          <el-table-column prop="name" label="姓名" align="center"  />
          <el-table-column prop="sex" label="性别"  align="center" />
          <el-table-column prop="age" label="年龄"  align="center" />
          <el-table-column prop="date" label="创建时间" width="300"  align="center" />
          <el-table-column width="300" label="操作" align="center" >
            <template slot-scope="scope">
              <el-button type="primary" size="min" icon="el-icon-plus" @click="addStuFn"></el-button>
              <el-button type="primary" size="min" icon="el-icon-edit" @click="updateFn(scope.row)"></el-button>
              <el-button type="primary" size="min" icon="el-icon-delete" @click="removeFn(scope.row.id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage4" :page-sizes="[3, 5, 7, 10]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog :title="isEdit ? '编辑学生信息' : '添加学生信息'" :visible.sync="addVisible" width="35%">
      <!-- 添加表单 -->
      <el-form :model="addForm" :rules="addRules" ref="addRef" lable-width="80px">
        <div></div>
        <el-form-item label="班级" prop="grade">
          <el-input v-model="addForm.grade" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <div>
          <el-form-item label="专业" prop="major">
            <el-input v-model="addForm.major" minlength="1" maxlength="10"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="addForm.name" minlength="1" maxlength="10"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="性别" prop="sex">
            <el-input v-model="addForm.sex" minlength="1" maxlength="10"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="addForm.age" minlength="1" maxlength="10"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancelFn">取 消</el-button>
        <el-button size="mini" type="primary" @click="addFn">添 加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getStuAPI, addStuAPI, updateStuAPI, delStuAPI } from "@/api/student";
export default {
  data() {
    return {
      tableData: [],
      addForm: {
        grade: '',
        major: '',
        name: '',
        sex: '',
        age: ''
      },
      inputName: '',
      currentPage4: 1,
      pageSize: 10,
      total: 20,
      editId: '',
      isEdit: false,
      addVisible: false,
      addRules: {
        grade: [
          { required: true, message: '请输入班级', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '班级必须是1-10位的非空字符', trigger: 'blur' }
        ],
        major: [
          { required: true, message: '请输入专业', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '专业必须是1-10位的非空字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名字', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '名字必须是1-10位的非空字符', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请输入性别', trigger: 'blur' },
          { pattern: /^\S{1,2}$/, message: '性别必须是1-2位的非空字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { pattern: /^\S{1,2}$/, message: '年龄必须是1-2位的非空字符', trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = 1
      this.pageSize = val
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage4 = val
    },
    search(bool) {
      if (bool) {
        let newListData = []
        if (this.inputName) {
          this.tableData.filter((item) => {
            if (item.name.indexOf(this.inputName) !== -1) {
              newListData.push(item)
            }
          });
        }
        this.tableData = newListData;
      } else {
        this.initGetStuFn()
      }
    },
    async initGetStuFn() {
      const res = await getStuAPI()
      if (res.status !== 200) {
        this.$message.error('获取学生数据失败!')
      } else {
        this.$message.success('获取学生数据成功!')
        this.tableData = res.data.data
        this.total = res.data.total
      }
    },
    // 对话框添加按钮事件
    async addFn() {
      this.$refs.addRef.validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            const { data: res } = await updateStuAPI({ id: this.editId, ...this.addForm })
            if (res.status !== 0) {
              this.$message.error('修改学生数据失败!')
            } else {
              this.$message.success('修改学生数据成功!')
            }
          } else {
            const { data: res } = await addStuAPI(this.addForm)
            if (res.status !== 0) {
              this.$message.error('添加学生数据失败！')
            } else {
              this.$message.success('添加学生数据成功！')
            }
          }
        }
        this.initGetStuFn()
        this.addVisible = false
        this.$refs.addRef.resetFields()
      })
    },
    // 对话框取消按钮事件
    cancelFn() {
      this.addVisible = false
      this.$refs.addRef.resetFields()
    },
    // 添加按钮回调
    addStuFn() {
      this.addVisible = true
      this.editId = ''
      this.isEdit = false
      this.$refs.addRef.resetFields()
    },
    // 修改按钮回调
    updateFn(obj) {
      this.editId = obj.id
      this.isEdit = true
      this.addVisible = true
      // 设置数据回显
      this.$nextTick(() => {
        this.addForm.grade = obj.grade
        this.addForm.major = obj.major
        this.addForm.name = obj.name
        this.addForm.sex = obj.sex
        this.addForm.age = obj.age
      })
    },
    // 删除按钮回调
    async removeFn(id) {
      const { data: res } = await delStuAPI(id)
      if(res.status !==0){
        this.$message.error('删除数据失败！')
      }else{
        this.$message.success('删除数据成功！')
        this.initGetStuFn()
      }
    }
  },
  watch: {
    inputName(newValue) {
      if (newValue) {
        this.search(true)
      } else {
        this.search(false)
      }
    }
  },
  created() {
    this.initGetStuFn()
  }
}
</script>

<style scoped>
.header-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 10px;
}
</style>
